package cn.edu.sctu.sctu_lysd.view.act;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import cn.edu.sctu.sctu_lysd.R;
import cn.edu.sctu.sctu_lysd.base.BaseActivity;
import cn.edu.sctu.sctu_lysd.cofig.CacheKeyConfig;
import cn.edu.sctu.sctu_lysd.utils.CacheImgPathUtil;
import cn.edu.sctu.sctu_lysd.utils.L;
import cn.edu.sctu.sctu_lysd.utils.SharePreferenceUtils;


/**
 * Created by 鑫爷您慢点 on 2016/8/3.
 */
public class OpenCameraActivity extends BaseActivity {
    private static final int CAMERA_WITH_DATA = 2000;
    private SharePreferenceUtils sharePreference;
    private Boolean is_create_team_flag = false;

    String imageName = "";


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.photo_show_photo;
    }

    @Override
    protected void initAfter(Object bind) {

        is_create_team_flag = getIntent().getExtras().getBoolean("flag_open_camera");

        sharePreference = SharePreferenceUtils.getInstance(this);
        UUID uuid = UUID.randomUUID();
        imageName = uuid + ".jpeg";
        sharePreference.setCache(CacheKeyConfig.CACHE_CAMERA_IMG_PATH, imageName);
        L.d("uuid11111",imageName);

        // 跳转至拍照界面
        Intent intentPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intentPhoto.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        File out = new File(getPhotoPath());
        Uri uri = Uri.fromFile(out);
        // 获取拍照后未压缩的原图片，并保存在uri路径中
        intentPhoto.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//        intentPhote.putExtra(MediaStore.Images.Media.ORIENTATION, 180);
        startActivityForResult(intentPhoto, CAMERA_WITH_DATA);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "当前存储卡不可用", Toast.LENGTH_SHORT).show();
            return;
        }

        if (requestCode == CAMERA_WITH_DATA && resultCode == Activity.RESULT_OK) {



            int degree = readPictureDegree(getPhotoPath());
            L.d("uuid22222",getPhotoPath());
            L.d("degree", degree + "");

            Bitmap bitmap = BitmapFactory.decodeFile(getPhotoPath());
            L.d("uuid33333",getPhotoPath());
            bitmap = toturn(bitmap, degree);

            savePhoto(bitmap, getPhotoPath());

            /**
             * 将拍照所得的图片路径加入到缓存
             */
            CacheImgPathUtil.getInstance(OpenCameraActivity.this).setCacheImgPath(getPhotoPath());

            sharePreference.removeOneCache(CacheKeyConfig.CACHE_CAMERA_IMG_PATH);

//            JumpUtils.jumpActivity(OpenCameraActivity.this, UploadNewsActivity.class);

            finish();
        } else if (resultCode == Activity.RESULT_CANCELED) {

            sharePreference.removeOneCache(CacheKeyConfig.CACHE_CAMERA_IMG_PATH);

//            JumpUtils.jumpActivity(OpenCameraActivity.this, UploadNewsActivity.class);

            finish();
        }
    }


    /**
     * 获取原图片存储路径
     *
     * @return
     */
    private String getPhotoPath() {
        // 照片全路径
        String fileName = "";
        // 文件夹路径
        String pathUrl = CacheKeyConfig.CACHE_HOME + "/";


        File file = new File(pathUrl);

        if (!file.exists()) {
            file.mkdirs();
        }

        fileName = pathUrl + sharePreference.getString(CacheKeyConfig.CACHE_CAMERA_IMG_PATH);

        L.d("uuid4444",fileName);

        return fileName;
    }

    /**
     * 存储缩放的图片
     *
     * @param
     */
    private void savePhoto(Bitmap bitmap, String path) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(path);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            // 用完了记得回收
            bitmap.recycle();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 读取照片exif信息中的旋转角度
     *
     * @param path 照片路径
     * @return角度
     */
    public int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    public Bitmap toturn(Bitmap img, int degree) {
        Matrix matrix = new Matrix();
        matrix.postRotate(+degree); /*翻转90度*/
        int width = img.getWidth();
        int height = img.getHeight();
        img = Bitmap.createBitmap(img, 0, 0, width, height, matrix, true);
        return img;
    }
}


